package com.sanpu.kxe.business.main.view;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;

import com.sanpu.kxe.R;
import com.sanpu.kxe.base.BaseFragmentActivity;
import com.sanpu.kxe.business.main.adapter.MainAdapter;
import com.sanpu.kxe.business.main.bean.ActHomePopOutput;
import com.sanpu.kxe.business.main.bean.CheckVersionOutput;
import com.sanpu.kxe.business.main.bean.UserCenterOutput;
import com.sanpu.kxe.business.main.contract.MainContract;
import com.sanpu.kxe.business.main.presenter.MainPresenter;
import com.sanpu.kxe.business.main.provider.MainOpenProvider;
import com.sanpu.kxe.business.trade.view.TransactionActivity;
import com.sanpu.kxe.common.cache.CacheManage;
import com.sanpu.kxe.common.cache.CacheModel;
import com.sanpu.kxe.common.interfaces.CommonConfig;
import com.sanpu.kxe.common.interfaces.DialogViewListener;
import com.sanpu.kxe.common.view.NoScrollViewPager;
import com.sanpu.kxe.jump.eventbus.OfflineEvent;
import com.sanpu.kxe.jump.eventbus.RefreshUserEvent;
import com.sanpu.kxe.module.dialog.CertificateDialog;
import com.sanpu.kxe.module.dialog.CheckVersionDialog;
import com.sanpu.kxe.module.dialog.GlobalDialog;
import com.sanpu.kxe.module.dialog.MaterialDialog;
import com.sanpu.kxe.module.dialog.PackageDialog;
import com.sanpu.kxe.module.immersionbar.ImmersionBar;
import com.sanpu.kxe.module.tablelayout.NavigationController;
import com.sanpu.kxe.module.tablelayout.PageBottomTabLayout;
import com.sanpu.kxe.module.tablelayout.item.BaseTabItem;
import com.sanpu.kxe.module.tablelayout.item.SpecialTab;
import com.sanpu.kxe.utils.AppContextUtil;
import com.sanpu.kxe.utils.IntentTool;
import com.sanpu.kxe.utils.ToastUtil;
import com.tencent.bugly.beta.Beta;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.math.BigDecimal;
import java.util.List;

import butterknife.Bind;

/**
 * Description：主界面
 * Created by 薛勇军 on 2018/6/12.
 */

public class MainActivity extends BaseFragmentActivity implements MainContract.View {

    @Bind(R.id.view_page)
    NoScrollViewPager vViewPager;
    @Bind(R.id.tab_bottom_layout)
    PageBottomTabLayout vTabBottomLayout;

    private MainAdapter mAdapter;
    private SpecialTab  myTab;
    private PackageDialog mPackageDialog;
    private ActHomePopupView actHomePopupView;
    private CheckVersionDialog checkVersionDialog;

    private long mLastClickBack;
    private boolean isShowAuthDialog = false;

    private MainContract.Presenter mPresenter;
    private GlobalDialog mNoticeDialog = null;
    private MaterialDialog mOfflineDialog = null;

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_main;
    }

    @Override
    protected void initImmersionBar() {
        mImmersionBar = ImmersionBar.with(this);
        mImmersionBar.statusBarColorTransformEnable(true)
                .statusBarDarkFont(true, 0.5f)
                .init();
    }

    /**
     * 构建"我的"tab
     */
    private BaseTabItem newMyItem(int drawable, int checkedDrawable, String text) {
        myTab = new SpecialTab(this);
        myTab.initialize(drawable, checkedDrawable, text);
        return myTab;
    }

    /**
     * 构建tab
     */
    private BaseTabItem newItem(int drawable, int checkedDrawable, String text) {
        SpecialTab mainTab = new SpecialTab(this);
        mainTab.initialize(drawable, checkedDrawable, text);
        return mainTab;
    }

    @Override
    protected void initView() {
        super.initView();
        mAdapter = new MainAdapter(getSupportFragmentManager());
        vViewPager.setOffscreenPageLimit(3);
        vViewPager.setNoScroll(false);
        NavigationController navigationController = vTabBottomLayout.custom()
                .addItem(newItem(R.drawable.oem_tab_homepage, R.drawable.oem_tab_homepage_pressed, "首页"))
//                .addItem(newItem(R.drawable.oem_tab_news, R.drawable.oem_tab_news_pressed, "资讯"))
                .addItem(newItem(R.drawable.oem_tab_share, R.drawable.oem_tab_share_pressed, "商学院"))
                .addItem(newMyItem(R.drawable.oem_tab_my, R.drawable.oem_tab_my_pressed, "我的"))
                .build();

        vViewPager.setAdapter(mAdapter);

        //自动适配ViewPager页面切换
        navigationController.setupWithViewPager(vViewPager);
        vViewPager.setCurrentItem(0);

        mPresenter = new MainPresenter(this);
        mPresenter.initPush();
    }

    @Override
    protected void initData() {
        super.initData();
        Beta.checkUpgrade(false,false);
        showNoticeDialog(getIntent());

        boolean isTransPush = getIntent().getBooleanExtra(CommonConfig.INTENT_ISTRANSPUSH, false);
        if (isTransPush) {
            IntentTool.startActivity(mContext, TransactionActivity.class);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        showNoticeDialog(intent);
    }

    /**
     * 推送通知消息弹框
     */
    private void showNoticeDialog(Intent intent) {
        try {
            String title = intent.getData().getQueryParameter("title");
            String content = intent.getData().getQueryParameter("content");
            mNoticeDialog = new GlobalDialog(mContext)
                    .title(title)
                    .content(content)
                    .gravity(Gravity.CENTER);
            mNoticeDialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mPresenter.onRequestUserCenter();
    }

    @Override
    public void refreshUserData(final UserCenterOutput output) {
        vViewPager.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (output != null) {
                    myTab.setHasMessage(output.hasMsgRead());
                    EventBus.getDefault().post(output);
                }
            }
        }, 50);
    }

    @Override
    public void showPackageDialog(UserCenterOutput.ActReb actReb) {
        if (actReb != null && ((actReb.getAmt() != null && actReb.getAmt().compareTo(BigDecimal.ZERO) == 1)
                || actReb.getBp() > 0)) {
            if (mPackageDialog == null) {
                mPackageDialog = new PackageDialog(mContext);
            }
            mPackageDialog.setData(actReb);
            mPackageDialog.setCancelable(false);
            mPackageDialog.setCanceledOnTouchOutside(false);
            mPackageDialog.show();
        }
    }

    @Override
    public void showActHomePopup(List<ActHomePopOutput> outputs) {
        if (outputs != null && outputs.size()>0) {
            if (checkVersionDialog != null && checkVersionDialog.isShowing()) {
                return;
            }
            if (actHomePopupView == null) {
                actHomePopupView = new ActHomePopupView(mContext, outputs);
            }
            actHomePopupView.setCancelClick(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    actHomePopupView.dismiss();
                    showAuthDialog();
                }
            });
            actHomePopupView.show();
        }
    }

    @Override
    public void showCheckVersionDialog(CheckVersionOutput checkVersionOutput) {
        if (checkVersionOutput != null) {
            if (actHomePopupView != null && actHomePopupView.isShowing()) {
                actHomePopupView.dismiss();
            }
            if (checkVersionDialog == null) {
                checkVersionDialog = new CheckVersionDialog(mContext, checkVersionOutput);
            }
            checkVersionDialog.show();
        }
    }

    /**
     * homepageFragment调用广告弹框
     */
    public void getActHomePopup() {
        mPresenter.getActHomePopup();
    }

    @Override
    public void showAuthDialog() {
        UserCenterOutput output = CacheManage.getInstance().getCache(CacheModel.USER_CENTER_KEY);
        if (!isShowAuthDialog && output != null && TextUtils.equals(CommonConfig.AUTHEN_NOTSUB, output.getChkSts())) {
            isShowAuthDialog = true;
            new CertificateDialog(mContext, new DialogViewListener() {
                @Override
                public void btnRightConfirm() {
                    MainOpenProvider.getInstance().openCertificationActivity(mContext);
                }

                @Override
                public void btnLeftCancel() {

                }
            }).show();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onOfflineEvent(OfflineEvent event) {
        if (event != null) {
            if (mOfflineDialog == null) {
                mOfflineDialog = new MaterialDialog(mContext)
                        .title("登录异常")
                        .content((CharSequence) event.getValues())
                        .autoDismiss(false);
                mOfflineDialog.setCancelable(false);
                mOfflineDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        AppContextUtil.exit(mContext);
                    }
                });
            }
            if (!mOfflineDialog.isShowing()) {
                mOfflineDialog.show();
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshUser(RefreshUserEvent event) {
        if (event != null) {
            mPresenter.onRequestUserCenter();
        }
    }

    @Override
    protected boolean hasBindEventBus() {
        return true;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (SystemClock.elapsedRealtime() - mLastClickBack < 2000) {
                mLastClickBack = 0;
                finish();
            } else {
                ToastUtil.show("再按一次退出");
                mLastClickBack = SystemClock.elapsedRealtime();
            }
        }
        return false;
    }

    @Override
    public void setPresenter(MainContract.Presenter presenter) {
        this.mPresenter = presenter;
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.onDestroyPresenter();
            mPresenter = null;
        }
        if (mPackageDialog != null && mPackageDialog.isShowing()) {
            mPackageDialog.dismiss();
            mPackageDialog = null;
        }
        if (mNoticeDialog != null && mNoticeDialog.isShowing()) {
            mNoticeDialog.dismiss();
            mNoticeDialog = null;
        }
        if (mOfflineDialog != null && mOfflineDialog.isShowing()) {
            mOfflineDialog.dismiss();
            mOfflineDialog = null;
        }
    }
}
